/**
 * 
 */
package com.fnic.pearl.scheduler.mod;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;

import com.fnic.pearl.scheduler.SchedulerConfig;
import com.fnic.pearl.scheduler.constant.CondHeaderField;
import com.fnic.pearl.scheduler.constant.SchedulerUrl;
import com.fnic.pearl.scheduler.constant.TestTaskStatus;
import com.fnic.pearl.scheduler.dao.SchedulerStore;
import com.fnic.pearl.scheduler.model.ProbeTaskStatus;
import com.fnic.pearl.scheduler.model.TestTask;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


/**
 * 测试任务状态处理器，主要负责：
 * 
 *  - 接收 并 解析 探针节点 上报的测试任务状态
 *  - 测试任务状态入队，并将此状态 上报 至 管理节点
 * 
 * @author HuHaiyang
 * @date 2013年7月16日
 */
public class TestTaskStatusHandler implements Runnable
{
    private static Logger LOG = Logger.getLogger(TestTaskStatusHandler.class);
    private String managerIp;
    private short managerPort;
    private String url;
    
    private Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    
    public TestTaskStatusHandler(String ip, short port)
    {
        this.managerIp = ip;
        this.managerPort = port;
        url = new StringBuilder().append("http://")
                .append(ip).append(":").append(port)
                .append(SchedulerUrl.TESTASK_STATUS_MANAGER)
                .append("?").append(CondHeaderField.COND_SCHEDULER_ID).append("=")
                .append(SchedulerConfig.getInstance().getSchedulerId())
                .toString();
    }
    
    /**
     * @see java.lang.Runnable#run()
     */
    public void run()
    {
        LOG.info("start test task status handler - " + managerIp + ":" + managerPort);
        while (!Thread.currentThread().isInterrupted())
        {
            List<ProbeTaskStatus> ptss = SchedulerStore.getInstance()
                    .popTestTaskStatuses(SchedulerConfig.getInstance().getMaxTTSNum());
            if (ptss != null && ptss.size() > 0)
            {
                HttpPost post = new HttpPost(url);
                try
                {
                    String json = gson.toJson(ptss);
                    StringEntity se = new StringEntity(json);
                    post.setEntity(se);
                    LOG.info("send task status: " + json);
                }
                catch (UnsupportedEncodingException e)
                {
                    LOG.warn("encoding testask status to json ex: " + e.getMessage());
                    post.releaseConnection();
                    continue;
                }
                
                ActiveToManager.getInstance().putRequest(post);
                for (ProbeTaskStatus pts : ptss)
                {
                    if (TestTaskSchedulerRuler.isEndStatus(pts))
                    {
                    	TestTask tt = null;
                    	if (pts.getStatus() == TestTaskStatus.S_EXEC_SUCC)
                    	{
                    		tt = SchedulerStore.getInstance().popExecSuccTestTask(
                    				pts.getProbeId(), pts.getTaskId());
                    	}
                    	else
                    	{
                    		tt = SchedulerStore.getInstance().popSFHTestTask(
                                    pts.getProbeId(), pts.getTaskId(), pts.getStatus());
                    	}
                        
                        if (tt != null)
                        {
                            tt.setStatus(TestTaskStatus.S_NEW_TASK);
                            SchedulerStore.getInstance().putInitTestTask(tt);
                        }
                    }
                }
            }
        }
    }
}
